import { useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Popconfirm,
  Radio,
  Space,
  Table,
  Tag,
  Tooltip,
  message
} from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import saveAs from 'file-saver';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { DefectAndWorkTicketStatusObj } from '@/enum/equipment';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equTicketBack,
  equTicketDelete,
  equTicketExport,
  equTicketIllegal,
  equTicketPage,
  equTicketSubmit
} from '@/services/bizApi/shebaogongzuopiaojiekou';
import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Audit, { AuditRef } from './audit';
import Dispose, { DisposeRef } from './dispose';
import Edit, { EditRef } from './edit';
import IsPass, { IsPassRef } from './ispass';
import StartPass, { StartPassRef } from './startpass';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.EquTicketResp;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const dispose = useRef<DisposeRef>(null);
  const audit = useRef<AuditRef>(null);
  const isPass = useRef<IsPassRef>(null);
  const startPass = useRef<StartPassRef>(null);
  const [visiable, setVisiable] = useState<boolean>(false);
  const [processLogList, setProcessLogList] = useState<BIZAPI.ProcessLogEntity[]>([]);
  const [filter] = Filter.useForm();
  const [illegalForm] = Form.useForm();
  const [visiableIllegal, setVisiableIllegal] = useState<boolean>(false);
  const [illegalId, setIllegalId] = useState<string>('');

  const handleExport = async (id: number, workTask: string) => {
    try {
      const response = await equTicketExport(
        {
          id
        },
        {
          skipErrorHandler: true,
          // tupleResponse: false,
          responseType: 'blob'
        }
      );

      if (response) {
        // const fileName = getFileNameFromAttachmentHeader(response.headers['content-disposition']);

        saveAs(response.data, `工作票-${workTask}.docx`);
      }
    } catch (error) {
      message.error('导出失败');
    }
  };

  const table = useAntdTable(
    async ({ current, pageSize }, { id, createTime, ...formData }) => {
      const [createTimeBegin, createTimeEnd] = ((createTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );
      const res = await equTicketPage({
        ...formData,
        ...id,
        createTimeBegin,
        createTimeEnd,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const handleIllegal = (id: string) => {
    setIllegalId(id);
    illegalForm.resetFields();
    setVisiableIllegal(true);
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() &&
              (store?.user?.roles?.includes('xjry') ||
                store?.user?.roles?.includes('scbzz') ||
                store?.user?.roles?.includes('yxry')) && (
                <Button
                  onClick={() => {
                    edit.current?.open({
                      type: 'add',
                      onSuccess: () => {
                        table.refresh();
                      }
                    });
                  }}
                  type="primary"
                >
                  新增
                </Button>
              )}
          </>
        }
      >
        {/* <Filter.Item name="defectNo">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入缺陷单号"
          />
        </Filter.Item>
        <Filter.Item name="defectType">
          <Select
            style={{ width: 180 }}
            placeholder="请选择缺陷类型"
            options={[
              {
                label: '设备缺陷',
                value: 1
              },
              {
                label: '生产缺陷',
                value: 2
              }
            ]}
          />
        </Filter.Item> 
        <Filter.Item name="createBy">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入上报人"
          />
        </Filter.Item>*/}
        <Filter.Item name="createTime">
          <DatePicker.RangePicker placeholder={['上报日期', '上报日期']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          // {
          //   title: '缺陷单号',
          //   dataIndex: 'defectNo'
          // },
          // {
          //   title: '工作任务',
          //   dataIndex: 'workTask'
          // },
          {
            title: '工作内容',
            dataIndex: 'defectDescription',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          // {
          //   title: '缺陷类型',
          //   dataIndex: 'defectType',
          //   render: (text) => (text === 1 ? '设备缺陷' : '生产缺陷')
          // },
          // {
          //   title: '上报人',
          //   dataIndex: 'createBy'
          // },
          {
            title: '上报时间',
            dataIndex: 'createTime',
            render: (text) => dayjs(text).format('YYYY-MM-DD')
          },
          {
            title: '状态',
            dataIndex: 'statusShow',
            render: (v) => {
              const item = v.replace(/\(/g, '').replace(/\)/g, '');
              const obj = DefectAndWorkTicketStatusObj.get(item);
              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              } else {
                return <span>{v}</span>;
              }
              // return emptyText;
            }
          },
          {
            title: '当前处理人',
            dataIndex: 'nextTargetList',
            render: (text, row) =>
              row?.nextTargetList?.map((item) => item?.nextOptTargetName)?.join('/')
          },
          {
            title: '危险点',
            dataIndex: 'dangerPoint',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip
                placement="top"
                title={
                  text
                    ? text.split(',').map((item: string, index: number) => (
                        <div key={index}>
                          {index + 1}.{item}
                        </div>
                      ))
                    : ''
                }
                arrow={true}
              >
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text ? text : ''}
                </div>
              </Tooltip>
            )
          },
          {
            title: '预控措施',
            dataIndex: 'protectiveMeasure',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip
                placement="top"
                title={
                  text
                    ? text.split(',').map((item: string, index: number) => (
                        <div key={index}>
                          {index + 1}.{item}
                        </div>
                      ))
                    : ''
                }
                arrow={true}
              >
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text ? text : ''}
                </div>
              </Tooltip>
            )
          },
          {
            title: '是否违规',
            dataIndex: 'illegal',
            render: (text, row) =>
              text ? <Text type="danger">是</Text> : <Text color="green">否</Text>
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              let bool = false;
              row?.nextTargetList?.forEach((item) => {
                console.log(store?.user?.id);
                if (item?.nextOptTargetType === 1 && store?.user?.id === item?.nextOptTargetId) {
                  bool = true;
                }
                if (
                  item?.nextOptTargetType === 2 &&
                  store?.user?.roleIds?.includes(item?.nextOptTargetId as unknown as number)
                ) {
                  bool = true;
                }
              });
              //判断打回是否显示 XX工程师
              let back: boolean = false;
              if (row?.defectType == 1) {
                //设备缺陷
                if (row?.faultType == '设备' && store?.user?.roles?.includes('sbgcs')) {
                  back = true;
                } else if (row?.faultType == '电器' && store?.user?.roles?.includes('dqgcs')) {
                  back = true;
                } else if (row?.faultType == '机械' && store?.user?.roles?.includes('jxgcs')) {
                  back = true;
                }
              } else {
                //生产缺陷
                if (store?.user?.roles?.includes('scgly') || store?.user?.roles?.includes('scbz')) {
                  back = true;
                }
              }

              return (
                <Text.Space limit={5}>
                  {permission.check() &&
                    bool &&
                    (row?.ticketStatus === 0 ||
                      row?.ticketStatus === 12 ||
                      row?.ticketStatus === 14 ||
                      row?.ticketStatus === 44) && (
                      <Popconfirm
                        title={`确定提交吗？`}
                        onConfirm={async () => {
                          const res = await equTicketSubmit({
                            id: row.id as unknown as string
                          });
                          store.app?.message.success(res.message);
                          table.refresh();
                          return res.success;
                        }}
                      >
                        <Text type="primary">提交</Text>
                      </Popconfirm>
                    )}
                  {permission.check() && bool && row?.ticketStatus === 10 && (
                    <Text
                      onClick={() => {
                        dispose.current?.open({
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      确认
                    </Text>
                  )}
                  {/* 关联缺陷的工作票打回 */}
                  {permission.check() &&
                    back &&
                    row?.ticketStatus === 11 &&
                    row?.defectId &&
                    row?.defectStatus != 44 && (
                      <Popconfirm
                        title={`确定打回吗？`}
                        onConfirm={async () => {
                          const res = await equTicketBack({
                            id: row.id as unknown as string
                          });
                          store.app?.message.success(res.message);
                          table.refresh();
                          return res.success;
                        }}
                      >
                        <Text type="primary">打回</Text>
                      </Popconfirm>
                    )}
                  {/* 未关联缺陷的工作票打回 */}
                  {permission.check() &&
                    row?.ticketStatus === 30 &&
                    !row?.defectId &&
                    (store?.user?.roles?.includes('scgly') ||
                      store?.user?.roles?.includes('scbz')) && (
                      <Popconfirm
                        title={`确定打回吗？`}
                        onConfirm={async () => {
                          const res = await equTicketBack({
                            id: row.id as unknown as string
                          });
                          store.app?.message.success(res.message);
                          table.refresh();
                          return res.success;
                        }}
                      >
                        <Text type="primary">打回</Text>
                      </Popconfirm>
                    )}
                  {/* {permission.check() && bool && row?.ticketStatus === 20 && (
                    <Text
                      onClick={() => {
                        audit.current?.open({
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      审核
                    </Text>
                  )} */}
                  {permission.check() && bool && row?.ticketStatus === 30 && (
                    <Text
                      onClick={() => {
                        startPass.current?.open({
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      发起验收
                    </Text>
                    // {/* <Popconfirm
                    //   title={`确定发起验收吗？`}
                    //   onConfirm={async () => {
                    //     const res = await equTicketStartCheck({
                    //       id: row.id as unknown as number,
                    //       toCheckAttachment: ''
                    //     });
                    //     store.app?.message.success(res.message);
                    //     table.refresh();
                    //     return res.success;
                    //   }}
                    // >
                    //   <Text type="primary">发起验收</Text>
                    // </Popconfirm> */}
                  )}
                  {permission.check() && bool && row?.ticketStatus === 40 && (
                    <Text
                      onClick={() => {
                        isPass.current?.open({
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      验收
                    </Text>
                  )}
                  {permission.check() &&
                    bool &&
                    (row?.ticketStatus === 0 ||
                      row?.ticketStatus === 12 ||
                      row?.ticketStatus === 14 ||
                      row?.ticketStatus === 44) && (
                      <Text
                        onClick={() => {
                          edit.current?.open({
                            type: 'edit',
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        编辑
                      </Text>
                    )}
                  {permission.check() &&
                    row?.ticketStatus &&
                    (row?.ticketStatus == 11 ||
                      row?.ticketStatus == 30 ||
                      row?.ticketStatus == 40 ||
                      row?.ticketStatus == 50) && (
                      <Text
                        onClick={() => {
                          // await equTicketExport({ id: row?.id });
                          handleExport(row?.id as unknown as number, row?.workTask as string);
                          // isPass.current?.open({
                          //   rowData: row,
                          //   onSuccess: () => {
                          //     table.refresh();
                          //   }
                          // });
                        }}
                        type="primary"
                      >
                        导出
                      </Text>
                    )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        setVisiable(true);
                        setProcessLogList(row?.processLogList || []);
                      }}
                      type="primary"
                    >
                      流程日志
                    </Text>
                  )}

                  {permission.check() &&
                    row?.ticketStatus === 0 &&
                    store?.user?.id === row?.createById && (
                      <Popconfirm
                        title={`确定删除吗？`}
                        onConfirm={async () => {
                          const res = await equTicketDelete({
                            id: row.id as unknown as string
                          });

                          store.app?.message.success(res.message);
                          table.refresh();

                          return res.success;
                        }}
                      >
                        <Text type="danger">删除</Text>
                      </Popconfirm>
                    )}
                  {permission.check() &&
                    row?.ticketStatus === 50 &&
                    store?.user?.roles?.includes('aqgcs') && (
                      <Text
                        type="danger"
                        onClick={() => {
                          handleIllegal(row.id as unknown as string);
                        }}
                      >
                        是否违规
                      </Text>
                    )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Dispose ref={dispose} />
      <Audit ref={audit} />
      <IsPass ref={isPass} />
      <StartPass ref={startPass} />
      <Modal
        width={1000}
        title="流程日志"
        open={visiable}
        footer={null}
        onCancel={() => {
          setVisiable(false);
          setProcessLogList([]);
        }}
      >
        <Table
          columns={[
            {
              title: '状态',
              dataIndex: 'dataStatus'
            },
            {
              title: '操作',
              dataIndex: 'description'
            },
            {
              title: '操作人',
              dataIndex: 'optUserName'
            },
            {
              title: '操作时间',
              dataIndex: 'optTime'
            },
            {
              title: '备注',
              dataIndex: 'remark',
              width: 120,
              ellipsis: true,
              render: (text) => (
                <Tooltip placement="top" title={text} arrow={true}>
                  <div
                    style={{
                      width: '120px',
                      wordBreak: 'break-all',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap'
                    }}
                  >
                    {text}
                  </div>
                </Tooltip>
              )
            }
          ]}
          dataSource={processLogList}
        />
      </Modal>

      <Modal
        width={500}
        title="是否违规"
        open={visiableIllegal}
        footer={null}
        onCancel={() => {
          setVisiableIllegal(false);
        }}
      >
        <Form
          form={illegalForm}
          onFinish={async (values) => {
            console.log(values);
            await equTicketIllegal({ ...values, id: illegalId });
            store.app?.message.success('操作成功');
            setVisiableIllegal(false);
            table.refresh();
          }}
        >
          <Form.Item
            name="illegal"
            label="是否违规"
            rules={[{ required: true, message: '请选择是否违规' }]}
          >
            <Radio.Group>
              <Radio value={true}>是</Radio>
              <Radio value={false}>否</Radio>
            </Radio.Group>
          </Form.Item>

          <ProFormSelect
            name="illegalTeamId"
            label="违规班组"
            placeholder="请选择违规班组"
            rules={[{ required: true, message: '请选择违规班组' }]}
            request={async () => {
              const res = await proShiftTeamPage({
                page: 1,
                size: 1000
              });
              return (
                res.data?.records?.map((item) => ({
                  value: item.id,
                  label: item.name
                })) || []
              );
            }}
          />
          <ProFormSelect
            name="illegalUserId"
            label="违规人员"
            placeholder="请选择违规人员"
            showSearch={true}
            rules={[{ required: true, message: '请选择违规人员' }]}
            request={async () => {
              const res = await orgUserInfoVoPage({
                page: 1,
                size: 1000
              });

              return (
                res?.data?.records?.map((item) => {
                  return {
                    label: item?.fullName,
                    value: item?.id
                  };
                }) || []
              );
            }}
          />

          <Form.Item
            name="illegalReason"
            label="违规原因"
            rules={[{ required: true, message: '请输入违规原因' }]}
          >
            <Input.TextArea placeholder="请输入违规原因" autoSize={{ minRows: 2, maxRows: 4 }} />
          </Form.Item>
          <Form.Item style={{ textAlign: 'center' }}>
            <Space>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button onClick={() => setVisiableIllegal(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Page;
